<template>
  <div class="car-dialog">
    <!-- start 车辆详情弹窗 -->
    <el-dialog
      title="车辆详情"
      :visible.sync="dialogCarInfoVisible"
      width="600px"
      @close="close"
      center
      class="car-dialog-container">
      <el-row :gutter="10" class="car-info-container">
        <el-col :span="24" class="title-h2">基础信息</el-col>
        <el-col :span="12" class="line">
          <span class="title">车型：</span>
          <span>{{carDetail.car_model_name}}</span>
        </el-col>
        <el-col :span="12" class="line">
          <span class="title">车牌号：</span>
          <span>{{carDetail.car_no}}</span>
        </el-col>
        <el-col :span="12" class="line">
          <span class="title">租赁价格：</span>
          <span style="color: blue; font-weight: 700; font-size: 16px">{{carDetail.rent_fee | unitFilter}}</span>/天
        </el-col>
        <el-col :span="12" class="line">
          <span class="title">交车城市：</span>
          <span>{{carDetail.car_city}}</span>
        </el-col>
        <el-col :span="12" class="line">
          <span class="title">押金金额：</span>
          <span style="color: blue; font-weight: 700; font-size: 16px">{{carDetail.deposit | unitFilter}}</span>
        </el-col>
        <div v-if="carRentRule">
          <el-col :span="24" class="title-h2">
            <span>出租规则</span>
            <el-button type="primary" size="mini" @click="carRule">编辑</el-button>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">取车地点：</span>
            <span>{{carRentRule.pickup_location}}</span>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">还车地点：</span>
            <span>{{carRentRule.return_location}}</span>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">取车时间：</span>
            <span>{{carRentRule.pickup_time | formatTime}}</span>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">还车时间：</span>
            <span>{{carRentRule.return_time | formatTime}}</span>
          </el-col>
        </div>
        <el-col :span="12" class="line">
          <span class="title">审核状态：</span>
          <span v-if="carDetail.audit_state === 0">待审核</span>
          <span v-if="carDetail.audit_state === 10">审核通过</span>
          <span v-if="carDetail.audit_state === 20">拒绝</span>
        </el-col>
        <el-col :span="12" class="line">
          <span class="title">是否可出租：</span>
          <span>{{carDetail.is_can_rent ? '是' : '否'}}</span>
        </el-col>
        <el-col :span="24" class="line-div">
          <div class="title" style="width: 100%">车辆描述：</div>
          <span>{{carDetail.summary}}</span>
        </el-col>
        <div v-if="carDetail.car_info">
          <el-col :span="24" class="title-h2">
            <span>车辆基础信息：</span>
            <el-button type="primary" size="mini" @click="carBasic">编辑</el-button>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">档位：</span>
            <span>{{carDetail.car_info.car_gear}}</span>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">车龄：</span>
            <span>{{carDetail.car_info.car_old | flit}}</span>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">租期需求：</span>
            <span>{{carDetail.car_info.lease_time}}</span>
          </el-col>
          <el-col :span="12" class="line">
            <span class="title">日均限行：</span>
            <span>{{carDetail.car_info.mileage}}</span>
          </el-col>
        </div>
        <el-col :span="24" class="title-h2">
          <span>行驶证图片：</span>
          <el-button type="primary" size="mini" @click="carPhoto('road_license_img')">编辑行驶证图片</el-button>
        </el-col>
        <el-col :span="24" class="car-img">
          <div class="img-list">
            <el-image class="images" v-for="(item, index) in carDetail.road_license_img" :preview-src-list=carDetail.road_license_img :key="index" :src="item" alt="行驶证图片" @error='imgLoad(item, index)'></el-image>
          </div>
        </el-col>
        <el-col :span="24" class="title-h2">
          <span>车辆图片：</span>
          <el-button type="primary" size="mini" @click="carPhoto('car_img')">编辑车辆图片</el-button>
        </el-col>
        <el-col :span="24" class="car-img">
          <div class="img-list">
            <el-image class="images" v-for="(item, index) in carDetail.car_img" :preview-src-list=carDetail.car_img :key="index" :src="item" alt="车辆图片"></el-image>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- end 车辆详情弹窗 -->
    <!-- 车辆档位信息弹窗 start-->
    <el-dialog title="车辆出租信息" :visible.sync="ruleFormVisible" width="30%" class="gearInfo">
      <div class="block">
        <span class="demonstration">取车地点</span>
        <el-input v-model="ruleForm.pickup_location" placeholder="请输入取车地点"></el-input>
      </div>
      <div class="block">
        <span class="demonstration">还车地点</span>
        <el-input v-model="ruleForm.return_location" placeholder="请输入还车地点"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ruleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="ruleClick">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车辆档位信息弹窗 start-->
    <!-- 车辆档位信息弹窗 start-->
    <el-dialog title="车辆基础信息" :visible.sync="dialogFormVisible" width="30%" class="gearInfo">
      <div class="block">
        <span class="demonstration">车辆档位信息</span>
        <el-select v-model="form.car_gear" placeholder="请选择车辆档位">
          <el-option
            v-for="item in car_gear_info"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="block">
        <span class="demonstration">车辆年龄</span>
        <el-select v-model="form.car_old" placeholder="请选择车辆年龄">
          <el-option
            v-for="item in car_old_info"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="block">
        <span class="demonstration">车辆租期要求</span>
        <el-select v-model="form.lease_time" placeholder="请选择车辆租期">
          <el-option
            v-for="item in lease_time_info"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="block">
        <span class="demonstration">车辆日限行</span>
        <el-input v-model="form.mileage" placeholder="请输入公里数"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="gearClick">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车辆档位信息弹窗 start-->
    <!-- start 图片放大弹窗 -->
    <el-dialog
      :visible.sync="dialogBigImg"
      width="600px"
      height="600px">
      <img width="100%" :src="bigImg" alt="图片">
    </el-dialog>
    <!-- end 图片放大弹窗 -->
    <!-- start 编辑车辆图片弹窗 -->
    <el-dialog
    :title="this.uploadName === 'car_img' ? '编辑车辆照片' : '编辑行驶证照片'"
    :visible.sync="editImgSync"
    width="30%">
    <el-upload
      action="#"
      list-type="picture-card"
      accept="image/jpeg, image/gif, image/png, image/bmp"
      ref="upload"
      :limit="5"
      :on-exceed="getFileExceed"
      :on-change="getFileChange"
      :auto-upload="false"
      :file-list="fileList"
      @closr="fileList = []">
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <el-image
            class="el-upload-list__item-thumbnail"
            :src="file.url" alt=""
            :preview-src-list="fileList"
            fit="cover"
          >
          </el-image>
          <!-- <el-progress type="circle" v-if="percentage" :percentage="percentage" :status="uploadStatus"></el-progress> -->
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in"></i>
            </span>
            <span
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editImgSync = false; fileList = []">取 消</el-button>
      <el-button type="primary" @click="uploadCarImg">确 定</el-button>
    </span>
  </el-dialog>
  <!-- end 编辑车辆图片弹窗 -->
  <el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
  </el-dialog>
  <div id="container"></div>
  </div>
</template>

<script>
// import COSImg from '../../cosImg.vue'
import { format } from 'date-fns'
import { regFenToYuan } from '@/utils/unitConversion'
import { putCar, patchLenderCarInfo, putCarRentRule, postCarGeom } from './server'
import COS from 'cos-js-sdk-v5'
import { getKey } from '../../../utils/comment'
import SparkMD5 from 'spark-md5'
import { COSName, Region } from '../../../utils/env'
export default {
  data () {
    return {
      model: {
        car_no: '', // 车牌号
        car_model_id: '', // 车辆的车型id
        pickup_location: '', // 取车详细地点信息
        return_location: '', // 还车详细地点信息
        pickup_longitude: null, // 取车地经度
        pickup_latitude: null, // 取车地维度
        pickup_time: '', // 取车时间
        return_time: '', // 还车时间
        rent_fee: '', // 租赁价格
        car_info: {
          car_gear: '',
          car_old: '',
          lease_time: '整月起租'
        } // 车辆基础信息
      },
      dialogCarInfoVisible: false,
      options: [], // 汽车品牌id
      city: [], // 城市三级联动数据
      pickup: '',
      carDetail: {}, // 车辆的详情信息,
      carRentRule: {}, // 车辆出租规则
      ruleFormVisible: false, // 出租信息弹窗
      dialogFormVisible: false, // 挡位信息弹窗
      ruleForm: {},
      form: {
        car_gear: '',
        car_old: '',
        lease_time: '',
        mileage: ''
      },
      car_gear_info: [
        {
          value: '手动挡',
          label: '手动挡'
        },
        {
          value: '自动挡',
          label: '自动挡'
        }],
      car_old_info: [
        {
          value: '半',
          label: '半年'
        },
        {
          value: '一',
          label: '一年'
        },
        {
          value: '二',
          label: '二年'
        },
        {
          value: '三',
          label: '三年'
        },
        {
          value: '四',
          label: '四年'
        },
        {
          value: '五',
          label: '五年'
        },
        {
          value: '六',
          label: '六年'
        },
        {
          value: '七',
          label: '七年'
        },
        {
          value: '八',
          label: '八年'
        },
        {
          value: '九',
          label: '九年'
        },
        {
          value: '十',
          label: '十年'
        },
        {
          value: '超过十',
          label: '超过十年'
        }],
      lease_time_info: [
        {
          value: '整月起租',
          label: '整月起租'
        },
        {
          value: '半年起租',
          label: '半年起租'
        },
        {
          value: '一年起租',
          label: '一年起租'
        }
      ],
      dialogBigImg: false, // 是否显示大图
      bigImg: '', // 图片的URL
      fileList: [],
      editImgSync: false, // 编辑车辆图片弹窗
      dialogVisible: false,
      dialogImageUrl: '',
      uploadName: '',
      watermarkOptions: {
        text: '仅供 礼租租车 服务使用',
        fontSize: 10,
        width: 5,
        color: '#ffffff',
        alpha: 35,
        rotate: 35,
        address: 'ssss'
      }
    }
  },
  methods: {
    close () {
      this.dialogCarInfoVisible = false
      this.$emit('close', false)
    },
    async save () {
      this.dialogCarInfoVisible = false
      this.$message({
        type: 'success',
        message: '新建成功'
      })
    },
    // 车辆品牌的联动
    carBrandChange (v) {
      this.model.car_model_id = v[2]
    },
    // 车辆出租规则打开弹窗
    carRule () {
      this.ruleFormVisible = true
      this.ruleForm = Object.assign({}, this.carRentRule)
    },
    // 车辆基本信息打开弹窗
    carBasic () {
      this.dialogFormVisible = true
      // 赋值选择框
      this.form.car_gear = this.carDetail.car_info.car_gear
      this.form.car_old = this.carDetail.car_info.car_old
      this.form.lease_time = this.carDetail.car_info.lease_time
      this.form.mileage = this.carDetail.car_info.mileage
    },
    // 修改出租位置信息
    async ruleClick () {
      await this.locationQuery(this.ruleForm.pickup_location)
      this.ruleFormVisible = false
    },
    // 经纬度查询
    locationQuery (name) {
      const that = this
      const map = new window.BMap.Map('container')
      const localSearch = new window.BMap.LocalSearch(map)
      map.clearOverlays()
      const keyword = name
      localSearch.setSearchCompleteCallback(async (searchResult) => {
        const poi = searchResult.getPoi(0)
        that.ruleForm.pickup_longitude = (poi.point.lng).toString()
        that.ruleForm.pickup_latitude = (poi.point.lat).toString()
        const data = {}
        data.lng = (poi.point.lng).toString()
        data.lat = (poi.point.lat).toString()
        const cargeom = await postCarGeom(data)
        if (cargeom && cargeom.code === 'ok') {
          that.ruleForm.the_geom = cargeom.data[0].geom
        }
        const res = await putCarRentRule(this.ruleForm)
        if (res && res.code === 'ok') {
          this.ruleFormVisible = false
          this.carRentRule = this.ruleForm
        }
      })
      localSearch.search(keyword)
    },
    // 修改车辆挡位信息
    async gearClick () {
      const data = {}
      data.car_info = Object.assign({}, this.form)
      data.id = this.carDetail.id
      const query = `?id=eq.${this.carDetail.id}`
      const res = await putCar(data, query)
      if (res && res.code === 'ok') {
        this.dialogFormVisible = false
        this.carDetail.car_info.car_gear = this.form.car_gear
        this.carDetail.car_info.car_old = this.form.car_old
        this.carDetail.car_info.lease_time = this.form.lease_time
        this.carDetail.car_info.mileage = this.form.mileage
        this.form = {
          car_gear: '',
          car_old: '',
          lease_time: '',
          mileage: ''
        }
        this.$message({
          type: 'success',
          message: '新建成功'
        })
      }
    },
    // 车辆基础照片信息
    lookImg (src) {
      this.dialogBigImg = true
      this.bigImg = src
    },
    carPhoto (name) {
      this.uploadName = name
      this.fileList = this.carDetail[name].map(item => { return { url: item } })
      this.editImgSync = true
    },
    // 查看车辆图片
    handlePictureCardPreview (file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    // 删除车辆图片
    handleRemove (file) {
      const index = this.fileList.findIndex(item => { return item.url === file.url })
      this.fileList.splice(index, 1)
    },
    // 图片列表上传超出数量
    getFileExceed (file, fileList) {
      this.$message.error('车辆图片超出限制')
    },
    // 选择图片时候触发
    getFileChange (file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 8
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 8MB!')
        fileList.forEach((item, index) => {
          if (item.name === file.name) {
            fileList.splice(index, 1)
          }
        })
      } else {
        this.fileList = fileList
      }
    },
    // 获取文件md5加密信息对比唯一性
    feachMd5 (file) {
      return new Promise((resolve, reject) => {
        var fileReader = new FileReader()
        var spark = new SparkMD5.ArrayBuffer()
        fileReader.readAsArrayBuffer(file)
        fileReader.onload = function (e) {
          spark.append(e.target.result)
          var md5 = spark.end()
          resolve({
            mds: md5
          })
        }
      })
    },
    // 压缩转base64
    dataURItoBlob (dataURI, type) {
      var binary = atob(dataURI.split(',')[1])
      var array = []
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], { type: type })
    },
    // 图片压缩 水印
    async compression (file, Watermark) {
      let max = ''
      if (file.size < 1000000) {
        max = 0.92
      } else if (file.size < 3000000) {
        max = 0.5
      } else {
        max = 0.3
      }
      const _this = this
      return new Promise(resolve => {
        const reader = new FileReader()
        const image = new Image()
        image.onload = (imageEvent) => {
          const column = 5
          const row = 3
          const canvas = document.createElement('canvas')
          const context = canvas.getContext('2d')
          const width = image.width * max
          const height = image.height * max
          canvas.width = width
          canvas.height = height
          context.clearRect(0, 0, width, height)
          _this.watermarkOptions.fontSize = '25px'
          context.drawImage(image, 0, 0, width, height)
          context.font = `${_this.watermarkOptions.fontSize} Arial`
          context.fillStyle = 'rgba(255, 255, 255, 0.5)'
          context.translate(0, 0)
          context.textAlign = 'end'
          context.textBaseline = 'middle'
          context.shadowColor = 'white'
          if (this.uploadName !== 'car_img') {
            for (var i = 0; i <= column * 1; i++) {
              for (var index = 0; index < row * 5; index++) {
                context.rotate(-25 * Math.PI / 180)
                context.fillText(`${_this.watermarkOptions.text}`, ((1360 / column) * (-i)), ((canvas.height / row) * (index + 1) / 2))
                context.fillText(`${_this.watermarkOptions.text}`, ((1360 / column) * (i)), ((canvas.height / row) * (index + 1) / 2))
                context.rotate(25 * Math.PI / 180)
              }
            }
          }
          const dataUrl = canvas.toDataURL(file.type)
          const blobData = _this.dataURItoBlob(dataUrl, file.type)
          const newfile = new window.File([blobData], file.name, { type: file.type })
          resolve(newfile)
        }
        reader.onload = e => { image.src = e.target.result }
        reader.readAsDataURL(file)
      })
    },
    // 上传车辆图片
    async uploadCarImg () {
      const files = []
      const fileUrlArr = []
      let key = ''
      for (const item of this.fileList) {
        if (item.raw) {
          const { mds } = await this.feachMd5(item.raw)
          const cp = await this.compression(item.raw, this.uploadName)
          if (this.uploadName === 'car_img') {
            key = 'img/car/'
          } else {
            key = 'img/carinfo/driving_license/'
          }
          files.push({
            Bucket: COSName, // Bucket 格式：BucketName-APPID
            Region: Region, // 存储桶所在地域，必须字段
            Key: key + mds,
            Body: cp
          })
        } else {
          fileUrlArr.push(item.url)
        }
      }
      const self = this
      if (files.length === 0) {
        self.editCarImg(fileUrlArr)
        return
      }
      this.cos.uploadFiles({
        files: files,
        SliceSize: 2048 * 2048,
        onProgress: function (info) {
        },
        onFileFinish: function (err, data, options) {
          if (err) {
            self.$message.error(options.Key + '上传失败')
          } else {
            self.$message.success(options.Key + '上传成功')
          }
        }
      }, function (err, data) {
        if (err) {
          self.$message.error('上传文件失败')
          return
        }
        data.files.forEach(item => {
          fileUrlArr.push('https://' + item.data.Location)
        })
        self.editCarImg(fileUrlArr)
      })
    },
    // 修改图片并获取车辆信息
    async editCarImg (fileUrlArr) {
      const data = {
        id: this.carDetail.id
      }
      data[`${this.uploadName}`] = fileUrlArr
      const res = await patchLenderCarInfo(data, {}, `?id=eq.${this.carDetail.id}`)
      if (!res || res.code !== 'ok') {
        this.$message.error('修改车辆图片失败')
        return
      }
      this.$message.success('修改车辆图片成功')
      this.fileList = []
      this.editImgSync = false
      this.carDetail[`${this.uploadName}`] = fileUrlArr
    },
    imgLoad (img, index) {
      img = img.split('com')[1]
      this.cos.getObjectUrl({
        Bucket: COSName,
        Region: Region,
        Key: img,
        Sign: true,
        Expires: 60
      }, (err, data) => {
        if (err) {
          this.$message.error('获取图片链接错误')
        }
        this.$set(this.carDetail.road_license_img, index, data.Url)
      })
    }
  },
  props: {
    flag: {
      type: Boolean,
      default: false
    },
    RentRule: {
      type: Object,
      default: function () {
        return {}
      }
    },
    carInfo: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  watch: {
    flag: {
      handler (newValue, oldValue) {
        this.dialogCarInfoVisible = newValue
      }
    },
    carInfo: {
      handler (newValue, oldValue) {
        this.carDetail = newValue
      }
    },
    RentRule: {
      handler (newValue, oldValue) {
        this.carRentRule = newValue
      }
    }
  },
  filters: {
    formatTime: function (val) {
      if (!val) return ''
      return format(new Date(val), 'yyyy-MM-dd HH:mm')
    },
    unitFilter: function (val) {
      if (!val) return '0.00 元'
      return regFenToYuan(val) + ' 元'
    },
    flit: function (val) {
      if (!val) return '未填写'
      return val + '年'
    }
  },
  async created () {
    const res = await getKey()
    if (!res || res.code !== 'ok') return
    const data = res.data
    const cos = new COS({
      getAuthorization: (options, callback) => {
        const obj = {
          TmpSecretId: data.credentials.tmpSecretId,
          TmpSecretKey: data.credentials.tmpSecretKey,
          XCosSecurityToken: data.credentials.sessionToken,
          StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
          ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000
        }
        callback(obj)
      }
    })
    this.cos = cos
  }
}
</script>

<style scoped lang="scss">
  @import './index.scss'
</style>
